/// CreateTime 2020/4/21 16:51
/// CreateUser chen 
/// ProjectName flutter_elf
import 'package:flutter_elf/config/component_index.dart';
import 'package:flutter_elf/utils/db/db_data.dart';

class DBPage extends BaseWidget{
  @override
  BaseWidgetState<BaseWidget> getState() {
    // TODO: implement getState
    return DBPageState();
  }
}

class DBPageState extends BaseWidgetState{
  List<DBDataResponse> data = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    updateData();
  }
  @override
  Widget buildView(BuildContext context) {
    // TODO: implement buildView
    return ListView(
      children: <Widget>[
        buildListItem('数据库是否存在', '点击验证', (){

        }),
        buildListItem('插入一条数据', 'insert', ()async{
          await DataDB.getInstance().insertOrReplaceToDB(DBDataResponse.fromMap({
            "data":"这是现在第${DateTime.now().millisecondsSinceEpoch}条数据",
            "id":DateTime.now().millisecondsSinceEpoch
          }));
          updateData();
        }),
        buildListItem('清除', 'clear', ()async{
          await DataDB.getInstance().clear();
          updateData();
        }),
        buildListItem('删除最后一条', 'delete', ()async{
          await DataDB.getInstance().deleteBook(data[data.length-1].id.toString());
          updateData();
        }),
        Text('数据'),
        Column(
          children: buildData(),
        ),
      ],
    );
  }

  updateData()async{
    data = await DataDB.getInstance().getAllData();
    setState(() {
    });
  }

  buildData(){
    return data.map((data){
      return Text('id' + data.id.toString() + '\n' + 'data' + data.data);
    }).toList();
  }

  buildListItem(String title,String text,VoidCallback onTap){
    return Row(children: <Widget>[
      Text('$title'),
      RaisedButton(
        onPressed: onTap,
        child: Text('$text'),
      ),
    ],);
  }

  @override
  PreferredSizeWidget initAppbar() {
    // TODO: implement initAppbar
    return AppBarCreator.create(context, '数据库测试');
  }
}